// RobotModel.js

class RobotModel {
    constructor() {
        // 机器人各个部件
        this.components = {
            body: null,
            wheels: [],
            cliffSensors: [],
            irSensors: [],
            tofSensor: null,
            lidar: null,
            lineLaser: null,
            frontBumper: null,
            powerButton: null,
            homeButton: null,
            lidarSwitches: [],
            waterTank: null,
            waterIndicator: null,
            dustBox: null,
            dustIndicator: null,
            sideBrushes: null,
            mainBrush: null,
            mop: null,
            battery: null,
            fan: null
        };
    }

    // 创建完整的机器人模型
    createRobotModel(config) {
        const robotGroup = new THREE.Group();

        // Create and add robot body
        this.components.body = this.createMainBodyModel(config);
        this.components.body.position.y = config.body.height / 2;
        robotGroup.add(this.components.body);

        // Create and add label
        this.addRobotBodyLabel(this.components.body, config);

        // Create and add water tank
        this.components.waterTank = this.createWaterTankModel(config);
        this.components.waterTank.position.set(-config.body.radius / 4, config.body.height / 7, -config.body.radius / 2);
        this.components.body.add(this.components.waterTank);

        // Create and add dust box
        this.components.dustBox = this.createDustBoxModel(config);
        this.components.dustBox.position.set(config.body.radius / 4, config.body.height / 7, -config.body.radius / 2);
        this.components.body.add(this.components.dustBox);

        // Create and add left wheel
        //this.components.wheels[0] = this.createWheelModel(config);
        this.components.wheels[0] = this.createEnhancedWheelModel(config);
        this.components.wheels[0].position.set(config.body.radius - config.wheels.radius, -config.body.height / 7, 0);
        this.components.wheels[0].rotation.z = Math.PI / 2;
        this.components.body.add(this.components.wheels[0]);

        // Create and add right wheel
        this.components.wheels[1] = this.createEnhancedWheelModel(config);
        this.components.wheels[1].position.set(-config.body.radius + config.wheels.radius, -config.body.height / 7, 0);
        this.components.wheels[1].rotation.z = Math.PI / 2;
        this.components.body.add(this.components.wheels[1]);

        // Create and add lidar
        const { combinedGroup, lidarGroup, staticGroup, switches, lidarBase, laserLine } = this.createLidarModel(config);
        combinedGroup.position.set(0, config.body.height / 2 + config.lidar.height / 3, config.lidar.radius * 3.3);
        this.components.body.add(combinedGroup);
        this.components.lidar = lidarGroup;
        this.components.lidarStatic = staticGroup;
        this.components.lidarSwitches = switches;
        this.components.lidarBase = lidarBase;
        this.components.lidarLaser = laserLine;

        // Create and add power button
        this.components.powerButton = this.createButtonModel(config, 'power');
        this.components.powerButton.position.set(-0.017, config.body.height / 2, config.body.radius - 0.024);
        this.components.body.add(this.components.powerButton);

        // Create and add recharge button
        this.components.homeButton = this.createButtonModel(config, 'recharge');
        this.components.homeButton.position.set(0.017, config.body.height / 2, config.body.radius - 0.024);
        this.components.body.add(this.components.homeButton);

        // Create and add bumper
        this.components.bumperGroup = this.createBumperModel(config);
        this.components.body.add(this.components.bumperGroup);

        // Create and add side brush
        this.components.sideBrushes = this.createSideBrushModel(config);
        this.components.sideBrushes.position.set(-config.body.radius + 0.06, -config.body.height / 2, config.body.radius - 0.06);
        this.components.body.add(this.components.sideBrushes);

        // Create and add main brush
        this.components.mainBrush = this.createMainBrushModel(config);
        this.components.mainBrush.position.set(-config.brushes.main.radius, -config.body.height * 0.32, config.brushes.main.radius);
        this.components.body.add(this.components.mainBrush);

        // Create and add mop
        switch(config.mop.type) {
            case 'rect':
                this.components.mop = this.createRectMopModel(config);
                break;
            case 'semicircle':
                this.components.mop = this.createSemicircleMopModel(config);
                break;
            case 'circle':
                this.components.mop = this.createCircleMopModel(config);
                break;
            default:
                console.warn('Unknown mop type:', config.mop.type);
                this.components.mop = this.createRectMopModel(config); // fallback to rectangular mop
        }
        //this.components.mop.position.set(0, -config.body.height / 2, -config.body.radius + config.mop.depth * 1.5);
        this.components.body.add(this.components.mop);

        // Create and add line laser
        this.components.lineLaser = this.createLineLaserModel(config);
        this.components.lineLaser.position.set(0, config.body.height / 2 - config.lineLaser.height * 1.5, config.body.radius);
        this.components.body.add(this.components.lineLaser);

        // Create and add cliff sensors
        const cliffSensorPositions = [
            { angle: -Math.PI/3, distance: config.body.radius - 0.01 },
            { angle: -Math.PI/12, distance: config.body.radius - 0.01 },
            { angle: Math.PI/12, distance: config.body.radius - 0.01 },
            { angle: Math.PI/3, distance: config.body.radius - 0.01 }
        ];
        cliffSensorPositions.forEach((pos, index) => {
            const sensor = this.createCliffSensorModel(config);
            sensor.position.set( Math.sin(pos.angle) * pos.distance, -config.body.height / 2, Math.cos(pos.angle) * pos.distance);
            sensor.rotation.set(0, pos.angle, 0);
            this.components.cliffSensors.push(sensor);
            this.components.body.add(sensor);
        });

        // Create and add IR sensors
        const irSensorPositions = [
            { angle: Math.PI * 17 / 12, height: config.body.height / 6 },
            { angle: Math.PI * 87 / 60, height: config.body.height / 6 },
            { angle: Math.PI * 89 / 60, height: config.body.height / 6 },
            { angle: Math.PI * 91 / 60, height: config.body.height / 6 },
            { angle: Math.PI * 93 / 60, height: config.body.height / 6 },
            { angle: Math.PI * 19 / 12, height: config.body.height / 6 }
        ];
        irSensorPositions.forEach((pos) => {
            const sensor = this.createIRSensorModel(config);
            sensor.position.set(
                Math.cos(pos.angle) * config.body.radius,
                pos.height,
                Math.sin(pos.angle) * config.body.radius
            );
            this.components.irSensors.push(sensor);
            this.components.body.add(sensor);
        });

        // Create and add TOF sensor
        this.components.tofSensor = this.createTOFSensorModel(config);
        this.components.tofSensor.position.set(-config.body.radius, config.body.height / 4 - config.tofSensor.height / 2, 0);
        this.components.tofSensor.rotation.y = Math.PI / 2;
        this.components.body.add(this.components.tofSensor);

        // Create and add FAN
        this.components.fan = this.createFanModel(config);
        //this.components.fan.position.set(-config.body.radius, config.body.height / 4, 0);
        this.components.fan.position.set(config.body.radius - config.fan.radius * 2, 0, -config.fan.radius * 2.5);
        //this.components.fan.rotation.y = Math.PI * 0.65; // 使风扇面向侧面
        this.components.fan.rotation.x = Math.PI / 2; // 使风扇面向正上
        this.components.body.add(this.components.fan);

        // Create and add battery
        this.components.battery = this.createCylindricalBatteryModel(config);
        this.components.body.add(this.components.battery);
        this.components.battery.position.set(config.body.height / 3, -config.body.height * 0.1, 0.08); // 调整位置到机器人前部
        this.components.battery.updateChargeLevel();

        // Create and add axis labels
        const { axesHelper, labelGroup } = this.createAxisLabels(config);
        this.components.axisObject = { axesHelper, labelGroup };
        this.components.body.add(axesHelper);

        // 初始化完成后，执行一次状态同步
        if (window.robotStateManager) {
            const initialState = window.robotStateManager.getState();
            if (window.componentManager) {
                window.componentManager.updateComponentsState(initialState.components);
            }
        }

        return robotGroup;
    }

    // 创建机器人主体
    createMainBodyModel(config) {
        const bodyGroup = new THREE.Group();

        // 主体
        const bodyMaterial = new THREE.MeshPhysicalMaterial({
            color: config.body.color,
            metalness: 0.5,
            roughness: 0.7,
            transparent: true,
            opacity: config.body.opacity,
            clearcoat: 0.8,
            clearcoatRoughness: 0.1,
            envMapIntensity: 0.5
        });

        const mainBodyGeometry = new THREE.CylinderBufferGeometry(
            config.body.radius,
            config.body.radius,
            config.body.height,
            config.body.vertice
        );
        const bodyMesh = new THREE.Mesh(mainBodyGeometry, bodyMaterial);
        bodyGroup.add(bodyMesh);

        return bodyGroup;
    }

    // 添加机身LOGO
    addRobotBodyLabel(robotBody, config) {
        // 直接使用原有的 addRobotBodyLabel 代码
        const bodyRadius = config.body.radius;
        const bodyHeight = config.body.height;

        const labelWidth = bodyRadius * 0.42;
        const labelHeight = bodyRadius * 0.2;
        const labelGeometry = new THREE.PlaneGeometry(labelWidth, labelHeight);

        const labelTexture = this.createRobotBodyLabelTexture(512, 256);
        const labelMaterial = new THREE.MeshBasicMaterial({
            map: labelTexture,
            transparent: true,
            side: THREE.DoubleSide
        });
        const labelMesh = new THREE.Mesh(labelGeometry, labelMaterial);

        labelMesh.position.set(0, bodyHeight / 2 + 0.0001, -bodyHeight * 2.3);
        labelMesh.rotation.x = -Math.PI / 2;
        labelMesh.rotation.z = Math.PI;

        robotBody.add(labelMesh);
    }

    // 创建机身LOGO纹理
    createRobotBodyLabelTexture(width, height) {
        // 直接使用原有的 createRobotBodyLabelTexture 代码
        const canvas = document.createElement('canvas');
        canvas.width = width;
        canvas.height = height;
        const context = canvas.getContext('2d');

        context.fillStyle = 'rgba(255, 255, 255, 0)';
        context.fillRect(0, 0, canvas.width, canvas.height);

        context.font = 'bold 80px Arial';
        context.fillStyle = 'black';
        context.textAlign = 'center';
        context.textBaseline = 'middle';
        context.fillText('ROBOT', canvas.width / 2, canvas.height / 2 - 42);
        context.fillText('CLEANER', canvas.width / 2, canvas.height / 2 + 42);

        return new THREE.CanvasTexture(canvas);
    }

    // 创建水箱
    createWaterTankModel(config) {
        const tankGeometry = new THREE.BoxBufferGeometry(
            config.waterTank.width,
            config.waterTank.height,
            config.waterTank.depth
        );
        const waterTankMaterial = new THREE.MeshPhysicalMaterial({
            color: new THREE.Color(config.waterTank.colorEmpty),
            clearcoat: 1,
            clearcoatRoughness: 0.1
        });
        const waterTank = new THREE.Mesh(tankGeometry, waterTankMaterial);
        return waterTank;
    }

    // 创建尘盒
    createDustBoxModel(config) {
        const boxGeometry = new THREE.BoxBufferGeometry(
            config.dustBox.width,
            config.dustBox.height,
            config.dustBox.depth
        );
        const dustBoxMaterial = new THREE.MeshPhysicalMaterial({
            color: new THREE.Color(config.dustBox.colorEmpty),
            clearcoat: 0.5,
            clearcoatRoughness: 0.3
        });
        const dustBox = new THREE.Mesh(boxGeometry, dustBoxMaterial);
        return dustBox;
    }

    // 创建普通轮子
    createWheelModel(config) {
        const wheelGeometry = new THREE.CylinderGeometry(
            config.wheels.radius,
            config.wheels.radius,
            config.wheels.width,
            config.wheels.vertice
        );
        const wheelMaterial = new THREE.MeshStandardMaterial({
            color: new THREE.Color(config.wheels.colorStatic),
            roughness: 0.7
        });
        const wheel = new THREE.Mesh(wheelGeometry, wheelMaterial);
        return wheel;
    }

    // 创建增强轮子
    createEnhancedWheelModel(config) {
        const wheelGeometry = new THREE.CylinderGeometry(
            config.wheels.radius,
            config.wheels.radius,
            config.wheels.width,
            32,
            1,
            false
        );

        // 创建轮胎纹理
        const texture = this.createWheelTexture();

        const wheelMaterial = new THREE.MeshPhongMaterial({
            color: new THREE.Color(config.wheels.colorStatic), // 添加基础颜色
            map: texture,
            bumpMap: texture,
            bumpScale: 0.02,
            side: THREE.DoubleSide
        });

        const wheel = new THREE.Mesh(wheelGeometry, wheelMaterial);
        wheel.rotation.x = Math.PI / 2;

        // 添加更新颜色的方法
        wheel.updateColor = function(newColor) {
            this.material.color.setHex(newColor);
        };

        return wheel;
    }

    // 创建轮胎纹理
    createWheelTexture() {
        const canvas = document.createElement('canvas');
        canvas.width = 512;
        canvas.height = 512;
        const context = canvas.getContext('2d');

        context.fillStyle = '#ffffff'; // 使用白色背景，让材质颜色更明显
        context.fillRect(0, 0, 512, 512);

        context.strokeStyle = '#cccccc'; // 使用浅灰色绘制花纹
        context.lineWidth = 10;

        // 绘制轮胎花纹
        for (let i = 0; i < 20; i++) {
            context.beginPath();
            context.moveTo(0, i * 25);
            context.lineTo(512, i * 25);
            context.stroke();

            context.beginPath();
            context.arc(256, 256, 200 - i * 10, 0, Math.PI * 2);
            context.stroke();
        }

        return new THREE.CanvasTexture(canvas);
    }

    // 创建激光雷达模型
    createLidarModel(config) {
        const lidarGroup = new THREE.Group();
        const staticGroup = new THREE.Group(); // 用于不旋转的部分

        // 雷达基座（可旋转部分）
        const lidarBaseGeometry = new THREE.CylinderGeometry(
            config.lidar.radius,
            config.lidar.radius,
            config.lidar.height,
            config.lidar.vertice
        );
        const lidarBaseMaterial = new THREE.MeshStandardMaterial({
            color: new THREE.Color(config.lidar.color),
            roughness: 0.3,
            metalness: 0.7
        });
        const lidarBase = new THREE.Mesh(lidarBaseGeometry, lidarBaseMaterial);
        lidarGroup.add(lidarBase);

        // 雷达罩子（静态部分）
        const lidarCoverGeometry = new THREE.CylinderGeometry(
            config.lidar.radius + 0.004,
            config.lidar.radius + 0.004,
            config.lidar.cover.height,
            config.lidar.vertice
        );
        const lidarCoverMaterial = new THREE.MeshPhysicalMaterial({
            color: new THREE.Color(config.lidar.cover.color),
            transparent: true,
            opacity: config.lidar.cover.opacity,
            metalness: 0.2,
            roughness: 0.1,
            clearcoat: 1,
            clearcoatRoughness: 0.1
        });
        const lidarCover = new THREE.Mesh(lidarCoverGeometry, lidarCoverMaterial);
        lidarCover.position.y = config.lidar.height / 2 + config.lidar.cover.height * 0.4;
        staticGroup.add(lidarCover);

        // 雷达支柱（静态部分）
        const pillarGeometry = new THREE.CylinderGeometry(
            config.lidar.pillars.radius,
            config.lidar.pillars.radius,
            config.lidar.height + config.lidar.cover.height,
            8
        );
        const pillarMaterial = new THREE.MeshStandardMaterial({
            color: new THREE.Color(config.lidar.cover.color),
            roughness: 0.5,
            transparent: true,
            opacity: config.lidar.cover.opacity,
            metalness: 0.5
        });
        for (let i = 0; i < 3; i++) {
            const pillar = new THREE.Mesh(pillarGeometry, pillarMaterial);
            pillar.position.y = config.lidar.cover.height / 2;
            pillar.position.x = Math.cos(i * Math.PI * 2 / 3) * (config.lidar.radius + 0.004 - config.lidar.pillars.radius);
            pillar.position.z = Math.sin(i * Math.PI * 2 / 3) * (config.lidar.radius + 0.004 - config.lidar.pillars.radius);
            staticGroup.add(pillar);
        }

        // 雷达底座开关（固定在底座周围）
        const switchGeometry = new THREE.CylinderGeometry(
            config.lidar.switches.radius,
            config.lidar.switches.radius,
            config.lidar.switches.height,
            config.lidar.vertice
        );
        const switchMaterial = new THREE.MeshPhongMaterial({
            color: new THREE.Color(config.lidar.switches.color),
            specular: 0x111111,
            shininess: 30
        });
        const switches = [];
        for (let i = 0; i < 4; i++) {
            const switchMesh = new THREE.Mesh(switchGeometry, switchMaterial.clone());
            const angle = i * Math.PI / 2;
            switchMesh.position.x = Math.cos(angle) * (config.lidar.radius + 0.01);
            switchMesh.position.z = Math.sin(angle) * (config.lidar.radius + 0.01);
            switchMesh.position.y = -config.lidar.height / 2 + config.lidar.switches.height * 2;
            switches.push(switchMesh);
            staticGroup.add(switchMesh); // 添加到静态部分，而不是旋转部分
        }

        // 创建激光线
        const laserGeometry = new THREE.BufferGeometry().setFromPoints([
            new THREE.Vector3(0, 0, 0),
            new THREE.Vector3(config.lidar.laserLength, 0, 0)
        ]);
        const laserMaterial = new THREE.LineBasicMaterial({
            color: config.lidar.laserColor,
            transparent: true,
            opacity: 0.3
        });
        const laserLine = new THREE.Line(laserGeometry, laserMaterial);
        laserLine.position.y = config.lidar.height / 4; // 将激光线置于雷达顶部
        laserLine.visible = false; // 初始时不可见
        lidarGroup.add(laserLine);

        const combinedGroup = new THREE.Group();
        combinedGroup.add(lidarGroup);
        combinedGroup.add(staticGroup);

        return { combinedGroup, lidarGroup, staticGroup, switches, lidarBase, laserLine };
    }

    // 创建按钮模型
    createButtonModel(config, buttonType) {
        const buttonGroup = new THREE.Group();

        // 确定按钮的几何形状和尺寸
        let buttonGeometry, ledGeometry;
        const scale = 1.0; // 增加按钮尺寸的比例

        buttonGeometry = new THREE.CylinderGeometry(
            config.buttons.radius * scale,
            config.buttons.radius * scale,
            config.buttons.height * scale,
            config.buttons.vertice
        );
        if (buttonType === 'recharge') {
            ledGeometry = new THREE.PlaneGeometry(
                config.buttons.width * scale * 0.9,
                config.buttons.width * scale * 0.9
            );
        } else {
            ledGeometry = new THREE.CircleGeometry(config.buttons.radius * scale * 0.55, 32);
        }

        // 创建按键主体
        const buttonMaterial = new THREE.MeshPhongMaterial({
            color: new THREE.Color(config.buttons.color),
            specular: 0x111111,
            shininess: 30
        });
        const buttonMesh = new THREE.Mesh(buttonGeometry, buttonMaterial);

        // 创建 LED 灯
        const ledMaterial = new THREE.MeshPhongMaterial({
            color: new THREE.Color(config.buttons.ledColor),
            emissive: new THREE.Color(config.buttons.ledColor),
            emissiveIntensity: 0,
            transparent: true,
            opacity: 0.5
        });
        const ledMesh = new THREE.Mesh(ledGeometry, ledMaterial);
        ledMesh.position.y = config.buttons.height * scale / 2 + 0.0001; // 略微放在按键上方
        ledMesh.rotation.x = -Math.PI / 2; // 使 LED 朝上

        buttonGroup.add(buttonMesh);
        buttonGroup.add(ledMesh);

        return buttonGroup;
    }

    // 创建前撞模型
    createBumperModel(config) {
        const bumperGroup = new THREE.Group();
        const outerRadius = config.body.radius + 0.005;
        const innerRadius = config.body.radius + 0.002;
        const shellHeight = 0.05;

        const points = [];
        points.push(new THREE.Vector2(innerRadius, 0));
        points.push(new THREE.Vector2(innerRadius, shellHeight));
        points.push(new THREE.Vector2(outerRadius, shellHeight));
        points.push(new THREE.Vector2(outerRadius, 0));

        const segments = 25; // 控制细节度
        const phiStart = Math.PI / 2;
        const phiLength = Math.PI / 2;

        // 创建左半部分
        const leftGeometry = new THREE.LatheGeometry(points, segments, phiStart, phiLength);
        const leftMaterial = new THREE.MeshPhysicalMaterial({
            color: new THREE.Color(config.bumper.colorStatic),
            transparent: true,
            opacity: config.bumper.opacity,
            metalness: 0.1,
            roughness: 0.3,
            clearcoat: 1,
            clearcoatRoughness: 0.1
        });
        const leftBumper = new THREE.Mesh(leftGeometry, leftMaterial);

        // 创建右半部分
        const rightGeometry = new THREE.LatheGeometry(points, segments, phiStart + Math.PI / 2, phiLength);
        const rightMaterial = leftMaterial.clone();
        const rightBumper = new THREE.Mesh(rightGeometry, rightMaterial);

        // 调整位置和旋转
        leftBumper.rotation.x = -Math.PI;
        rightBumper.rotation.x = -Math.PI;
        leftBumper.position.set(0, shellHeight / 2, 0);
        rightBumper.position.set(0, shellHeight / 2, 0);

        bumperGroup.add(leftBumper);
        bumperGroup.add(rightBumper);

        return bumperGroup;
    }

    // 创建边刷
    createSideBrushModel(config) {
        const brushGroup = new THREE.Group();
        const armMaterial = new THREE.MeshPhongMaterial({ color: new THREE.Color(config.brushes.side.colorStatic) });

        for (let i = 0; i < config.brushes.side.number; i++) {
            const armShape = new THREE.Shape();
            armShape.moveTo(0, 0);
            armShape.lineTo(0, 0.4);
            armShape.lineTo(-0.03, 0.4);
            armShape.lineTo(-0.03, 0.2);

            const extrudeSettings = {
                steps: 1,
                depth: 0.005,
                bevelEnabled: false
            };

            const armGeometry = new THREE.ExtrudeGeometry(armShape, extrudeSettings);
            const arm = new THREE.Mesh(armGeometry, armMaterial);
            arm.rotation.z = Math.PI / 2; // 使臂垂直
            arm.rotation.y = (i * 2 * Math.PI) / config.brushes.side.number; // 在 Y 轴上均匀分布
            arm.scale.set(0.2, 0.2, 0.2); // 缩小到原来的20%

            brushGroup.add(arm);
        }

        return brushGroup;
    }

    // 创建普通主刷
    createMainBrushModel(config) {
        const mainBrushGeometry = new THREE.CylinderGeometry(
            config.brushes.main.radius,
            config.brushes.main.radius,
            config.brushes.main.length,
            config.brushes.main.vertice
        );
        const mainBrushMaterial = new THREE.MeshPhongMaterial({
            color: new THREE.Color(config.brushes.main.colorStatic)
        });
        const mainBrush = new THREE.Mesh(mainBrushGeometry, mainBrushMaterial);
        mainBrush.rotation.z = Math.PI / 2;
        return mainBrush;
    }

    // 创建增强主刷
    createEnhancedMainBrushModel(config) {
        const brushGroup = new THREE.Group();

        // 主刷芯
        const coreGeometry = new THREE.CylinderGeometry(
            config.brushes.main.radius * 0.6,
            config.brushes.main.radius * 0.6,
            config.brushes.main.length,
            32
        );
        const coreMaterial = new THREE.MeshPhongMaterial({
            color: config.brushes.main.colorStatic
        });
        const coreMesh = new THREE.Mesh(coreGeometry, coreMaterial);
        brushGroup.add(coreMesh);

        // 添加刷毛
        const bristleCount = 1000; // 刷毛数量
        const bristleGeometry = new THREE.CylinderGeometry(0.0005, 0.0005, config.brushes.main.radius * 0.4, 3);
        const bristleMaterial = new THREE.MeshPhongMaterial({
            color: 0x888888,
            shininess: 30
        });

        for (let i = 0; i < bristleCount; i++) {
            const bristle = new THREE.Mesh(bristleGeometry, bristleMaterial);
            const theta = Math.random() * Math.PI * 2;
            const y = Math.random() * config.brushes.main.length - config.brushes.main.length / 2;
            bristle.position.set(
                Math.cos(theta) * config.brushes.main.radius * 0.6,
                y,
                Math.sin(theta) * config.brushes.main.radius * 0.6
            );
            bristle.rotation.x = Math.PI / 2;
            bristle.rotation.z = theta;
            brushGroup.add(bristle);
        }

        brushGroup.rotation.z = Math.PI / 2;
        return brushGroup;
    }

    // 创建半月形拖布
    createSemicircleMopModel(config) {
        const radius = config.body.radius; // 圆弧半径
        const thickness = 0.003; // 拖布厚度
        const angle = Math.PI * 0.62;
        const chordHeight = radius * 0.2; // 弦到圆心的距离，控制弓的"胖瘦"

        const shape = new THREE.Shape();

        // 计算弦的端点
        const startX = radius * Math.cos(angle / 2);
        const startY = radius * Math.sin(angle / 2);

        // 绘制圆弧
        shape.moveTo(startX, startY);
        shape.absarc(0, 0, radius, angle / 2, -angle / 2, true);

        // 绘制直线（弦）
        shape.lineTo(startX, startY);

        shape.closePath();

        const extrudeSettings = {
            steps: 1,
            depth: thickness,
            bevelEnabled: false
        };

        const geometry = new THREE.ExtrudeGeometry(shape, extrudeSettings);
        const material = new THREE.MeshStandardMaterial({
            color: new THREE.Color(config.mop.colorStatic),
            roughness: 0.8,
            metalness: 0.1
        });

        const mop = new THREE.Mesh(geometry, material);

        // 调整拖布的位置和旋转
        mop.rotation.x = -Math.PI / 2; // 使拖布平放
        mop.rotation.z = Math.PI / 2; // 使拖布平放
        mop.position.y = -config.body.height / 2 - thickness * 0.9; // 将拖布放置在底部
        mop.position.z = -config.body.radius * 0.02 ; // 稍微向后调整

        return mop;
    }

    // 设置圆形拖布位置
    setCircularMopPosition(angle) {
        if (robot.mop && robot.mop.pivot) {
            // 假设拖布可以在半径为 config.mop.moveRadius 的范围内移动
            const radius = robotConfig.mop.moveRadius;
            const x = Math.cos(angle) * radius;
            const z = Math.sin(angle) * radius;
            robot.mop.pivot.position.set(x, 0, z);
        }
    }

    // 创建圆形拖布
    createCircleMopModel(config) {
        const geometry = new THREE.CylinderGeometry(
            config.mop.width / 2,
            config.mop.width / 2,
            config.mop.depth,
            32
        );
        const material = new THREE.MeshStandardMaterial({
            color: new THREE.Color(config.mop.colorStatic),
            roughness: 0.8,
            metalness: 0.1
        });

        const mopGroup = new THREE.Group();
        const mopMesh = new THREE.Mesh(geometry, material);
        mopMesh.rotation.x = Math.PI / 2; // 使圆柱体平躺
        mopGroup.add(mopMesh);

        // 添加一个不可见的对象作为移动的pivot点
        const pivot = new THREE.Object3D();
        pivot.position.set(0, 0, 0);
        mopGroup.add(pivot);
        pivot.add(mopMesh);

        // 将pivot点保存在mopGroup中，以便后续访问
        mopGroup.pivot = pivot;

        return mopGroup;
    }

    // 创建矩形拖布
    createRectMopModel(config) {
        const mopGeometry = new THREE.BoxGeometry(
            config.mop.width,
            config.mop.height,
            config.mop.depth
        );
        const mopMaterial = new THREE.MeshStandardMaterial({
            color: new THREE.Color(config.mop.colorStatic),
            roughness: 0.8,
            metalness: 0.1
        });
        return new THREE.Mesh(mopGeometry, mopMaterial);
    }

    // 创建线激光
    createLineLaserModel(config) {
        const laserGroup = new THREE.Group();

        // 创建激光发射器主体
        const laserGeometry = new THREE.BoxGeometry(
            config.lineLaser.width,
            config.lineLaser.height,
            config.lineLaser.depth
        );
        const laserMaterial = new THREE.MeshStandardMaterial({
            color: new THREE.Color(config.lineLaser.color),
            emissive: new THREE.Color(config.lineLaser.color),
            emissiveIntensity: 1
        });
        const laserMesh = new THREE.Mesh(laserGeometry, laserMaterial);
        laserGroup.add(laserMesh);

        const points = {
            A: new THREE.Vector3(config.lineLaser.lines[0].ax, config.lineLaser.lines[0].ay, config.lineLaser.lines[0].az),
            B: new THREE.Vector3(config.lineLaser.lines[1].bx, config.lineLaser.lines[1].by, config.lineLaser.lines[1].bz),
            C: new THREE.Vector3(config.lineLaser.lines[2].cx, config.lineLaser.lines[2].cy, config.lineLaser.lines[2].cz),
            D: new THREE.Vector3(config.lineLaser.lines[3].dx, config.lineLaser.lines[3].dy, config.lineLaser.lines[3].dz),
            E: new THREE.Vector3(config.lineLaser.lines[4].ex, config.lineLaser.lines[4].ey, config.lineLaser.lines[4].ez),
            F: new THREE.Vector3(config.lineLaser.lines[5].fx, config.lineLaser.lines[5].fy, config.lineLaser.lines[5].fz)
        };

        // 创建激光线材质
        const laserLineMaterial = new THREE.LineBasicMaterial({
            color: 0xff0000,
            transparent: true,
            opacity: 0.1
        });
        const laserLineMaterialGround = new THREE.LineBasicMaterial({
            color: 0xFF00FF,
            transparent: true,
            opacity: 0.7
        });

        // 创建激光线
        const createLaserLine = (start, end) => {
            const geometry = new THREE.BufferGeometry().setFromPoints([start, end]);
            return new THREE.Line(geometry, laserLineMaterial);
        };

        const createLaserLineGround = (start, end) => {
            const geometry = new THREE.BufferGeometry().setFromPoints([start, end]);
            return new THREE.Line(geometry, laserLineMaterialGround);
        };

        const laserLines = [
            createLaserLine(points.E, points.A),
            createLaserLine(points.E, points.B),
            createLaserLine(points.F, points.C),
            createLaserLine(points.F, points.D),
        ];
        const laserLinesGround = [
            createLaserLineGround(points.A, points.B),
            createLaserLineGround(points.C, points.D)
        ];

        laserLines.forEach(line => {
            line.visible = false;
            laserGroup.add(line);
        });

        laserLinesGround.forEach(line => {
            line.visible = false;
            laserGroup.add(line);
        });

        laserGroup.laserLines = laserLines;
        laserGroup.laserLinesGround = laserLinesGround;

        return laserGroup;
    }

    // 创建悬崖传感器
    createCliffSensorModel(config) {
        const cliffSensorGeometry = new THREE.BoxGeometry(
            config.cliffSensors.width,
            config.cliffSensors.height,
            config.cliffSensors.depth
        );
        const cliffSensorMaterial = new THREE.MeshStandardMaterial({
            color: new THREE.Color(config.cliffSensors.color),
            roughness: 0.5,
            metalness: 0.2,
            emissive: new THREE.Color(config.cliffSensors.activeColor),
            emissiveIntensity: 0
        });
        return new THREE.Mesh(cliffSensorGeometry, cliffSensorMaterial);
    }

    // 创建红外传感器
    createIRSensorModel(config) {
        const irSensorGeometry = new THREE.SphereGeometry(config.irSensors.radius, 16, 16);
        const irSensorMaterial = new THREE.MeshStandardMaterial({
            color: new THREE.Color(config.irSensors.color),
            emissive: new THREE.Color(config.irSensors.activeColor),
            emissiveIntensity: 0.5
        });
        return new THREE.Mesh(irSensorGeometry, irSensorMaterial);
    }

    // 创建TOF传感器
    createTOFSensorModel(config) {
        const tofGroup = new THREE.Group();

        // 创建 TOF 传感器主体
        const tofGeometry = new THREE.BoxGeometry(
            config.tofSensor.width,
            config.tofSensor.height,
            config.tofSensor.depth
        );
        const tofMaterial = new THREE.MeshStandardMaterial({
            color: new THREE.Color(config.tofSensor.color),
            roughness: 0.5,
            metalness: 0.5
        });
        const tofMesh = new THREE.Mesh(tofGeometry, tofMaterial);
        tofGroup.add(tofMesh);

        // 创建表示测量距离的线
        const lineMaterial = new THREE.LineBasicMaterial({
            color: config.tofSensor.activeColor,
            transparent: true,
            opacity: 0.9
        });
        const lineGeometry = new THREE.BufferGeometry().setFromPoints([
            new THREE.Vector3(0, 0, 0),
            new THREE.Vector3(0, 0, 1)  // 初始长度为1，将在更新函数中调整
        ]);
        const distanceLine = new THREE.Line(lineGeometry, lineMaterial);
        distanceLine.visible = false;  // 初始状态为不可见
        tofGroup.add(distanceLine);

        // 将距离线存储在 tofGroup 中，以便后续可以访问
        tofGroup.distanceLine = distanceLine;

        return tofGroup;
    }

    // 创建圆柱形电池模型
    createCylindricalBatteryModel(config) {
        const batteryGroup = new THREE.Group();
        const totalLength = config.battery.totalLength; // 电池总长度
        const batteryRadius = config.battery.batteryRadius; // 电池半径
        const positivePoleRadius =
            config.battery.batteryRadius * config.battery.positivePoleRatio; // 正极半径
        const positivePoleHeight = config.battery.positivePoleHeight; // 正极高度

        // 创建绿色部分（电量指示器）
        const greenGeometry = new THREE.CylinderGeometry(batteryRadius, batteryRadius, totalLength, 32);
        const greenMaterial = new THREE.MeshPhongMaterial({ color: 0x00FF00 });
        const greenMesh = new THREE.Mesh(greenGeometry, greenMaterial);
        greenMesh.rotation.z = Math.PI / 2; // 横放
        batteryGroup.add(greenMesh);
        batteryGroup.greenMesh = greenMesh;
        batteryGroup.greenMaterial = greenMaterial;

        // 创建灰色部分（已用电量）
        const grayGeometry = new THREE.CylinderGeometry(batteryRadius, batteryRadius, totalLength, 32);
        const grayMaterial = new THREE.MeshPhongMaterial({ color: 0xCCCCCC });
        const grayMesh = new THREE.Mesh(grayGeometry, grayMaterial);
        grayMesh.rotation.z = Math.PI / 2; // 横放
        batteryGroup.add(grayMesh);
        batteryGroup.grayMesh = grayMesh;
        batteryGroup.grayMaterial = grayMaterial;

        // 创建正极（黄色小圆柱）
        const positivePoleGeometry = new THREE.CylinderGeometry(positivePoleRadius, positivePoleRadius, positivePoleHeight, 32);
        const positivePoleMaterial = new THREE.MeshPhongMaterial({ color: 0xFFD700 }); // 金色
        const positivePoleMesh = new THREE.Mesh(positivePoleGeometry, positivePoleMaterial);
        positivePoleMesh.rotation.z = Math.PI / 2; // 横放
        positivePoleMesh.position.set(totalLength / 2 + positivePoleHeight / 2, 0, 0);
        batteryGroup.add(positivePoleMesh);

        // 创建 LED 显示窗
        const displayWidth = config.batteryWindow.displayWidth;  // LED显示窗宽度
        const displayHeight = config.batteryWindow.displayHeight; // LED显示窗高度
        const displayGeometry = new THREE.PlaneGeometry(displayWidth, displayHeight);
        const displayMaterial = new THREE.MeshPhongMaterial({
            map: this.createBatteryDisplayTexture(100), // 初始显示100%
            emissive: 0x333333,
            emissiveMap: this.createBatteryDisplayTexture(100),
            emissiveIntensity: 0.3, // 降低发光强度
            transparent: true,
            opacity: 0.95
        });

        const displayMesh = new THREE.Mesh(displayGeometry, displayMaterial);
        // 调整位置，确保完全贴合在机身表面
        displayMesh.position.set(-config.body.radius * 0.07,
            config.body.height / 2 + 0.01,
            -config.body.radius * 0.6);
        displayMesh.rotation.x = -Math.PI / 2;
        displayMesh.rotation.z = -Math.PI / 2;
        batteryGroup.add(displayMesh);
        batteryGroup.displayMesh = displayMesh;
        batteryGroup.displayMaterial = displayMaterial;
        batteryGroup.totalLength = totalLength;


        // 更新电量显示的方法
        batteryGroup.updateChargeLevel = this.updateBatteryChargeLevel.bind(this, batteryGroup);

        return batteryGroup;
    }

    createBatteryDisplayTexture(percentage) {
        try {
            const canvas = document.createElement('canvas');
            canvas.width = 512;
            canvas.height = 356;
            const context = canvas.getContext('2d');

            // 清除画布
            context.clearRect(0, 0, canvas.width, canvas.height);

            // 设置透明背景
            context.fillStyle = 'rgba(255, 255, 255, 0)';
            context.fillRect(0, 0, canvas.width, canvas.height);

            // 绘制电量文字
            context.font = 'bold 200px Arial';
            context.fillStyle = 'yellow';
            context.textAlign = 'center';
            context.textBaseline = 'middle';
            context.fillText(`${percentage}%`, canvas.width / 2, canvas.height / 2);

            return new THREE.CanvasTexture(canvas);
        } catch (error) {
            console.error('Error creating battery display texture:', error);
            return null;
        }
    }

    // 更新电池电量显示的方法
    updateBatteryChargeLevel(batteryGroup) {
        // 确保 robotStateManager 已经初始化
        if (!window.robotStateManager) {
            console.warn('robotStateManager not initialized yet');
            return;
        }

        const level = window.robotStateManager.getState().robot.battery;
        const percentage = Math.round(level * 100);

        console.log("Update battery level:", level, "percentage:", percentage);

        // 更新电池主体颜色和比例
        if (level > 0.2) {
            batteryGroup.greenMaterial.color.setHex(0x00FF00); // 绿色
        } else {
            batteryGroup.greenMaterial.color.setHex(0xFF0000); // 红色
        }

        // 更新电量显示部分的比例
        batteryGroup.greenMesh.scale.y = level;
        batteryGroup.greenMesh.position.x = -(1 - level) * batteryGroup.totalLength / 2;
        batteryGroup.grayMesh.scale.y = 1 - level;
        batteryGroup.grayMesh.position.x = level * batteryGroup.totalLength / 2;

        // 更新 LED 显示纹理
        const newTexture = this.createBatteryDisplayTexture(percentage);
        batteryGroup.displayMaterial.map = newTexture;
        batteryGroup.displayMaterial.emissiveMap = newTexture;

        // 根据电量调整显示亮度
        batteryGroup.displayMaterial.emissiveIntensity = level > 0.2 ? 0.3 : 0.4;

        // 确保材质更新
        batteryGroup.displayMaterial.needsUpdate = true;
        batteryGroup.greenMaterial.needsUpdate = true;
        batteryGroup.grayMaterial.needsUpdate = true;
    }

    // 创建风机模型
    createFanModel(config) {
        const fanGroup = new THREE.Group();

        // 创建风扇外框
        const frameGeometry = new THREE.TorusGeometry(config.fan.radius, config.fan.frameThickness, 16, 100);
        const frameMaterial = new THREE.MeshPhongMaterial({
            color: config.fan.frameColor,
            shininess: 30
        });
        const frameMesh = new THREE.Mesh(frameGeometry, frameMaterial);
        fanGroup.add(frameMesh);

        // 创建扇叶组
        const bladesGroup = new THREE.Group();

        // 创建扇叶
        const bladeShape = new THREE.Shape();
        bladeShape.moveTo(0, 0);
        bladeShape.lineTo(config.fan.bladeLength, config.fan.bladeWidth / 2);
        bladeShape.lineTo(config.fan.bladeLength, -config.fan.bladeWidth / 2);
        bladeShape.lineTo(0, 0);

        const bladeGeometry = new THREE.ShapeGeometry(bladeShape);
        const bladeMaterial = new THREE.MeshPhongMaterial({
            color: config.fan.bladeColor,
            side: THREE.DoubleSide,
            shininess: 50
        });

        for (let i = 0; i < config.fan.bladeCount; i++) {
            const blade = new THREE.Mesh(bladeGeometry, bladeMaterial);
            blade.rotation.z = (i / config.fan.bladeCount) * Math.PI * 2;
            bladesGroup.add(blade);
        }

        fanGroup.add(bladesGroup);

        // 创建风扇中心
        const centerGeometry = new THREE.CylinderGeometry(
            config.fan.centerRadius,
            config.fan.centerRadius,
            config.fan.thickness,
            32
        );
        const centerMaterial = new THREE.MeshPhongMaterial({
            color: config.fan.centerColor,
            shininess: 50
        });
        const centerMesh = new THREE.Mesh(centerGeometry, centerMaterial);
        centerMesh.rotation.x = Math.PI / 2;
        fanGroup.add(centerMesh);

        // 将扇叶组存储在 fanGroup 中，以便后续访问
        fanGroup.bladesGroup = bladesGroup;

        return fanGroup;
    }

    // 创建坐标轴标签
    createAxisLabels(config) {
        const axesHelper = new THREE.AxesHelper(config.axisHelper.size);
        const labelGroup = new THREE.Group();

        const offsets = [
            new THREE.Vector3(config.axisHelper.labelOffsets[0].x, config.axisHelper.labelOffsets[0].y, config.axisHelper.labelOffsets[0].z),
            new THREE.Vector3(config.axisHelper.labelOffsets[1].x, config.axisHelper.labelOffsets[1].y, config.axisHelper.labelOffsets[1].z),
            new THREE.Vector3(config.axisHelper.labelOffsets[2].x, config.axisHelper.labelOffsets[2].y, config.axisHelper.labelOffsets[2].z),
        ];

        config.axisHelper.labels.forEach((label, index) => {
            const labelDiv = document.createElement('div');
            labelDiv.className = 'axis-label';
            labelDiv.textContent = label;
            labelDiv.style.color = `#${config.axisHelper.colors[index].toString(16).padStart(6, '0')}`;
            labelDiv.style.fontSize = config.axisHelper.fontSize;

            const labelObject = new THREE.CSS2DObject(labelDiv);
            const position = new THREE.Vector3().setComponent(index, config.axisHelper.size);
            position.add(offsets[index]);  // 添加偏移量
            labelObject.position.copy(position);
            axesHelper.add(labelObject);
        });

        return { axesHelper, labelGroup };
    }

    // 更新坐标轴标签
    updateAxisLabels(axisObject, camera) {
        if (!axisObject || !axisObject.labelGroup) return;

        axisObject.labelGroup.children.forEach((label, index) => {
            const worldPosition = new THREE.Vector3();
            worldPosition.setFromMatrixPosition(axisObject.axesHelper.matrixWorld);

            const axisEnd = new THREE.Vector3();
            axisEnd.setComponent(index, axisObject.axesHelper.scale.x);
            axisEnd.applyMatrix4(axisObject.axesHelper.matrixWorld);

            const labelPosition = worldPosition.clone().add(axisEnd.sub(worldPosition).multiplyScalar(1.1));

            label.position.copy(labelPosition);
            label.element.style.display = isInViewFrustum(label.position, camera) ? '' : 'none';
        });
    }

    isInViewFrustum(position, camera) {
        const frustum = new THREE.Frustum();
        frustum.setFromProjectionMatrix(new THREE.Matrix4().multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse));
        return frustum.containsPoint(position);
    }

    initCSS2DRenderer(container) {
        labelRenderer = new THREE.CSS2DRenderer();
        labelRenderer.setSize(container.clientWidth, container.clientHeight);
        labelRenderer.domElement.style.position = 'absolute';
        labelRenderer.domElement.style.top = '0px';
        labelRenderer.domElement.style.pointerEvents = 'none';
        container.appendChild(labelRenderer.domElement);
        return labelRenderer;
    }

    // 获取组件
    getComponent(name) {
        return this.components[name];
    }

    // 更新组件
    updateVisualComponent(name, component) {
        if (this.components.hasOwnProperty(name)) {
            this.components[name] = component;
        }
    }

    // 其他组件的创建方法先预留...
    createAndAddComponents(config) {
        // 这里预留其他组件的创建和添加
        // 后续我们可以逐步添加每个组件的创建代码
    }
}

// 创建全局单例
const robotModel = new RobotModel();

// 导出到全局作用域
if (typeof window !== 'undefined') {
    window.robotModel = robotModel;
    window.RobotModel = RobotModel;
}

// CommonJS 模块导出
if (typeof module !== 'undefined' && module.exports) {
    module.exports = {
        RobotModel,
        robotModel
    };
}
